<template>
  <div v-if="isDisplay">
      <Row style="margin-top: 5px;" :gutter="8"> 
          <!-- 同租人搜索框 -->
          <Col :span="isRenterDetail ? 4 : 7">
                <Select
                    filterable
                    clearable
                    remote
                    placeholder="租客姓名/手机号"
                    v-model="idNameAndPhone"
                    :remote-method="remoteRenterMethod"
                    :loading="loadingRenter"
                    @on-change="selectData">
                    <Option v-for="(option, index) in searchedRenters" :label="option.name +'-'+ option.phone" :value="option.id + '-' + option.name +'-'+ option.phone" :key="index">{{option.name +'-'+ option.phone}}</Option>
                </Select>
          </Col>
          <!-- 同租人关系下拉框 -->
          <Col :span="isRenterDetail ? 4 : 7">
                <Select v-model="relationship">
                    <Option v-for="item in relations" :value="item.value" :key="item.value">{{ item.text }}</Option>
                </Select>
          </Col>

          <!-- 只有当外门或者哪门可以发放授权密码 -->
          <Col span="3" v-if="inlineLock || outLock">
            <DatePicker 
                type="datetime" 
                placement="bottom" 
                placeholder="租约开始日期" 
                :options="startOption" 
                v-model="checkInDateStart"
                :disabled="!sendOnlinePwdOrNot"
                style="width:100%"></DatePicker>
          </Col>

          <Col span="3" v-if="inlineLock || outLock">
            <DatePicker 
                type="datetime" 
                placement="bottom" 
                placeholder="租约结束日期"
                :options="endOption"  
                v-model="checkInDateEnd"
                style="width:100%"></DatePicker>
          </Col>

          <Col span="10" class="position:relative;top:6px;">
            <Checkbox v-model="isSendFaceAuth" v-if="faceDevices.length">下发人脸门禁授权</Checkbox>
            <Checkbox v-model="isSendM3Auth" v-if="guardM3Devices.length">将租客可开门门禁授权给同租人</Checkbox>
            <Checkbox v-model="sendOutDoorPwd" v-if="outLock">下发外门锁密码</Checkbox>
            <Checkbox v-model="sendInlineDoorPwd" v-if="inlineLock">下发内门锁密码</Checkbox>
            <Checkbox v-model="smsWithHome" v-if="inlineLock || outLock"> 短信携带公寓信息</Checkbox>

            <Button type="ghost" @click="handleCancel">删除</Button>
            <Button type="ghost" @click="save" v-if="isRenterDetail">保存</Button>
          </Col>

          <Col span="24" v-if="!sendOnlinePwdOrNot && (sendOutDoorPwd || sendInlineDoorPwd)">
            <p style="padding: 5px 0">当前有门锁离线或无网关，只能下发离线密码</p>
          </Col>
      </Row>
  </div>
</template>

<script>
import { http, api } from '@/libs/http'
import { CoRenterRelations } from '@/libs/const'
import dayjs from 'dayjs'
export default {
  data () {
    return {
      // idNameAndPhone: '',
      leaseEndTime: null, // 租约结束时间
      checkInDateEnd: null,
      isSendFaceAuth: true, // 是否发放门禁授权
      isSendM3Auth: true, // 是否下发m3门禁授权
      checkInDateStart: new Date(), // 租约开始时间
      smsWithHome: false, // 下发短信是否携带公寓地址
      sendInlineDoorPwd: false, // 是否下发内门密码,
      sendOutDoorPwd: false, // 是否下发外门锁密码,
      locks: [], // 内外门锁
      isDisplay: true, // 控制组件是否进行展示
      loadingRenter: false,
      searchedRenters: [],
      renterId: '', // 新增同租人租客id
      relationship: '亲属',
      idNameAndPhone: '', // 用户id-用户name-用户电话号码
      relations: CoRenterRelations.properties, // 所有亲属关系
      startOption: {
        disabledDate (date) {
          return date && date.valueOf() < new Date().valueOf() - 86400000
        }
      },
      guardM3Devices: [], // M3门禁设备
      guardM3DevicesIds: [] // M3门禁ID
    }
  },

  props: {
    faceDevices: {
      type: Array,
      default: () => []
    },
    homeId: Number,
    corIndex: {
      // 同租人序列号
      require: true,
      type: Number
    },
    isRenterDetail: { // 是否是租客详情
      default: false,
      type: Boolean
    },
    leaseId: {
      type: Number
    },
    roomId: {
      type: Number
    },
    tenantId: {
      // 承租人id
      require: false,
      type: String
    },
    leaseRange: { // 租约范围
      type: Array
    }
  },

  watch: {
    relationship (newVal) {
      // 如果亲属关系发生变化时并且在入住弹窗中同步数据
      if (this.renterId !== '' && !this.isRenterDetail) this.selectData(this.idNameAndPhone, newVal)
    },
    sendOnlinePwdOrNot (value) {
      if (value) {
        this.checkInDateEnd = dayjs(this.leaseRange[1]).toDate()
      } else {
        this.checkInDateEnd = dayjs(Math.min(dayjs(this.leaseRange[1]).valueOf(), dayjs(this.checkInDateStart).add(365, 'day').valueOf())).toDate()
      }
    }
  },

  computed: {
    endOption () {
      return {
        disabledDate: (date) => { // 如果是离线密码，时间有效期不能超过一年
          return !this.sendOnlinePwdOrNot ? date && (date.valueOf() < Date.now() - 86400000 || date.valueOf() > dayjs(this.checkInDateStart).add(365, 'day').valueOf()) : date && date.valueOf() < Date.now() - 86400000
        }
      }
    },

    inlineLock () { // 是否有内门锁
      return this.locks.find((lock) => lock.is_public === false)
    },

    outLock () { // 是否有外门锁
      return this.locks.find((lock) => lock.is_public === true)
    },

    sendInlineDoorOnlinePwd () { // 是否可以发放内门在线密码
      if (this.inlineLock && this.inlineLock.can_send_online_password) {
        return true
      } else {
        return false
      }
    },

    sendOutDoorOnlinePwd () { // 是否可以发放外门在线密码
      if (this.outLock && this.outLock.can_send_online_password) {
        return true
      } else {
        return false
      }
    },

    passwordMultiType () { // 发放密码类型
      if (this.sendInlineDoorPwd && !this.sendOutDoorPwd) { // 只选了内门
        return 1
      } else if (!this.sendInlineDoorPwd && this.sendOutDoorPwd) { // 只选了外门
        return 2
      } else if (this.sendInlineDoorPwd && this.sendOutDoorPwd) { // 内外门都选了
        return 3
      } else { // 内外门都没选
        return 0
      }
    },

    sendOnlinePwdOrNot () { // 发放在线密码还是离线密码
      return [false, this.sendInlineDoorOnlinePwd, this.sendOutDoorOnlinePwd, this.sendInlineDoorOnlinePwd && this.sendOutDoorOnlinePwd][this.passwordMultiType]
    }
  },

  mounted () {
    if (this.roomId) {
      this.leaseEndTime = dayjs(this.leaseRange[1]).toDate()
      this.checkInDateStart = dayjs(this.leaseRange[0]).toDate() // 如果是租客详情进来的默认时间为租约开始时间
      this.checkInDateEnd = dayjs(Math.min(dayjs(this.leaseRange[1]).valueOf(), dayjs(this.checkInDateStart).add(365, 'day').valueOf())).toDate()
      this.getLocksDetail()
      this.fetchM3AccessControll(this.roomId)
    }
  },

  methods: {

    /**
        * 获取m3门禁信息
        */
    async fetchM3AccessControll (roomId) {
      try {
        this.guardM3Devices = await http.fetch(this, api.m3_pre_add_tenant_info, [roomId])

        this.guardM3DevicesIds = this.guardM3Devices.map((device) => (device.id))
      } catch (error) {
        console.log('err', error)
      }
    },

    /**
         *  搜索租客
         * @param {} query 搜索条件
         */
    remoteRenterMethod (query) {
      if (query !== '') {
        let params = {
          keyword: query,
          limit: 500
        }
        this.loadingRenter = true
        http.request(this, api.tenant_list, null, params, res => {
          if (res) {
            this.searchedRenters = res.list
          }
          this.loadingRenter = false
        })
      } else {
        this.searchedRenters = []
      }
    },

    /**
        * 获取门锁信息详情
        */
    getLocksDetail () {
      http.request(this, api.room_lock_detail, [this.roomId], null, (res, error) => {
        if (error || !res) {
          return
        }

        const { locks } = res
        this.locks = locks
      })
    },

    /**
         * 存储相关数据
         * @param {String} id 返回数据是以 id-name-phone作为存在的
         */
    selectData (idNameAndPhone) {
      if (!this.isRenterDetail) {
        // 如果在入住弹窗中
        const obj = idNameAndPhone.split('-')
        this.renterId = obj[0]
        this.storeData(obj, this.relationship)
      } else {
        // 如果在租客详情中，返回数据是以 id-name-phone作为存在的
        if (idNameAndPhone) this.idNameAndPhone = idNameAndPhone
      }
    },

    /**
         * @param {String} 租客id
         * @param {String} 租客关系
         */
    storeData (...options) {
      // console.log('options', options);
      let params = {
        tenant_id: Number(options[0][0]),
        name: options[0][1],
        phone: options[0][2],
        relationship: options[1]
      }
      this.$emit('addCorenterData', params, this.corIndex)
    },

    /**
         * 前端假删除列表显示
         */
    handleCancel () {
      this.isDisplay = false
      this.$emit('removeCorenterData', this.corIndex)
    },

    async authorizeM3 (co_tenant_id) {
      try {
        await http.fetch(this, api.m3_co_tenant_auth_add, [this.leaseId, co_tenant_id])

        this.$Message.success('同租人m3门禁授权下发成功')
      } catch (error) {
        console.log('error', error)
      }
    },

    async authorize (relation_id) {
      const [startTime, endTime] = this.leaseRange
      const params = {
        auth_start_time: new Date(startTime).valueOf(),
        auth_end_time: new Date(endTime).valueOf(),
        device_ids: this.faceDevices.map((device) => (device.id)),
        relation_role: 2,
        relation_id,
        lease_id: this.leaseId
      }
      try {
        await http.fetch(this, api.face_access_add, [this.homeId], params, true)

        this.$Message.success('同租人人脸门禁授权下发成功')
      } catch (error) {
        console.log('error', error)
      }
    },

    /**
         * 新增单个同租人
         */
    save () {
      if (this.idNameAndPhone === '') {
        this.$Message.info('请先选择租客!')
        return
      }

      let arr = this.idNameAndPhone.split('-') // 将字符串改变为数组arr[0]，arr[1]，arr[2]分别为id，name和phone

      if (this.tenantId === arr[0]) {
        // 限制不能添加同租人为自己本身
        this.$Message.info('不能添加自己为同租人!')
        return
      }

      if (this.passwordMultiType) {
        if (new Date(this.checkInDateEnd).valueOf() > new Date(this.leaseEndTime).valueOf()) {
          this.$Message.error('密码下发时间不能大于租约结束时间!')
          return
        }
      }

      let params = {
        co_tenants: [
          {
            tenant_id: Number(arr[0]),
            relationship: this.relationship
          }
        ]
      }

      http.request(this, api.tenant_co_add, [this.leaseId], params, (res, err) => {
        // 添加同租人
        if (err) return

        if (this.isSendFaceAuth && this.faceDevices.length) { // 如果勾选同租人下发门禁授权的话
          this.authorize(Number(arr[0]))
        }
        if (this.isSendM3Auth && this.guardM3Devices.length) { // 如果勾选同租人下发门禁授权的话
          this.authorizeM3(Number(arr[0]))
        }
        this.$Message.success('添加同租人成功!')
        this.handleCancel()
        this.$emit('addCoTenants', arr)
      })

      if (this.passwordMultiType) { // 如果选择了内门或者外门
        const params = {
          password_type: 1,
          country_code: '86',
          // name: arr[1],
          room_id: this.roomId,
          lease_id: this.leaseId,
          tenant_id: Number(arr[0]),
          // phonenumber: arr[2],
          is_send_location: this.smsWithHome,
          permission_status: 2,
          multi_type: this.passwordMultiType,
          permission_begin: new Date(this.checkInDateStart).valueOf(),
          permission_end: new Date(this.checkInDateEnd).valueOf()
        }

        http.request(this, this.sendOnlinePwdOrNot ? api.password_send_multi : api.password_send_active_multi, [this.roomId], params, (res, error) => {
          if (error) {
            return
          }

          this.$Message.success('同租人密码下发成功!')
        })
      }
    }
  }
}
</script>
<style lang='less' scoped>
</style>